<?php
/* the short url will be consisting of 2 parts : xxyyyyyy..
xx is the ascii sum of each character in url, converted in base 62 MyNumber
yyyy... is the MyNumber of latest auto increment ID
the shortest url will be xxyy (4 chars).. the xx is to make the url secret, cannot be guessed by another user
*/
require_once("connect.php");
require_once("MyNumber.php");
$url = $_POST["url"];
$url = trim($url);
$fullUrl = $url;
//do the shorten
//remove the http/ftp and www
$pos = strpos($url,"://");
if($pos !== false){
	$url = substr($url,$pos+3);
}
if(substr($url,0,3) == "www"){
	$url = substr($url,4);
}
$result = "";
//calculate the total ascii of all character, limit to max 62*62-1 (2 digits of base 62 MyNumber)
//or limit to max 20 char only, to fasten
$limChar = 20;
$limSum = pow(MyNumber::base,2)-1;
$sum = 0;
for($i=0;$i<strlen($url);$i++){
	$asci = ord($url[$i]);
	if($sum+$asci >= $limSum) break;
	$sum += $asci;
	if($i+1 >= $limChar) break;
}
$urlSum = new MyNumber($sum);
//store to database
$owner = (logged()?user(1):-1);
//the stored url to db is only the xx ($urlSum) part, no need the $urlId
mysqli_query($db,"insert into urltable values(0,'$urlSum','$fullUrl',$owner)");
$newId = mysqli_insert_id($db);
echo getShortUrl($urlSum,$newId);
?>

